package ecom.shell.commandsImpl;

import ecom.shell.exception.InsuffisantPrivilegeException;
import ecom.beans.ProductcategoryBean;
import ecom.beans.EcomAdminRemote;
import ecom.beans.EcomCustomerRemote;
import ecom.shell.commandsImpl.OutputCommandImpl.Outputs;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringWriter;
import java.util.Set;
import java.util.StringTokenizer;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import shell.ShellCommand;
import shell.ShellContext;

public class ProductcategoryCommands implements ShellCommand {

    private ShellContext _context = null;

    public ProductcategoryCommands(ShellContext context) {
        _context = context;
    }

    @Override
    public String getName() {
        return "productcategory";
    }

    @Override
    public String getUsage() {
        return "productcategory ";
    }

    @Override
    public String getShortDescription() {
        String commands = "Productcategory commands :\n";
        if (true == _context.getVar("isAdmin")) {
            commands += "\t[without args] ................get all productcategories\n";
            commands += "\t-help .........................get productcategory commands description\n";
            commands += "\t-add [name]....................create a new category\n";
            commands += "\t-remove [Productcategory id]...remove a category\n";
        }
        return commands;
    }

    @Override
    public String execute(String cmdline, PrintStream out, PrintStream err) throws InsuffisantPrivilegeException {
        StringBuilder result = new StringBuilder();
        StringTokenizer cmd = new StringTokenizer(cmdline, " ");

        EcomAdminRemote ecomAdminBean = (EcomAdminRemote) _context.getVar("adminBean");
        EcomCustomerRemote ecomCustomerBean = (EcomCustomerRemote) _context.getVar("customerBean");
        Outputs currentOutput = (Outputs) _context.getVar("output");
        Set<ProductcategoryBean> categoryList = null;

        cmd.nextToken();

        if (cmd.countTokens() == 0) {
            categoryList = ecomCustomerBean.getAllCategories(null);
            try {
                return printList(out, categoryList, currentOutput);
            } catch (Exception ex) {
                System.err.println("Error with getting all produccategories : " + ex.getMessage());
            }
        } else {
            String arg = cmd.nextToken();

            if (arg.equals("-help")) {
                result.append(getShortDescription());
            } else if (arg.equals("-add")) {
                if (true != _context.getVar("isAdmin")) {
                    throw new InsuffisantPrivilegeException();
                }
                if (cmd.countTokens() == 1) {
                    try {
                        String name = cmd.nextToken();

                        ecomAdminBean.createProductcategory(name);
                        Long id = ecomAdminBean.getProductcategoryByName(name).getIdProductcategory();
                        result.append("Productcategory created with id : ").append(id);
                    } catch (Exception e) {
                        err.println("Error with account creation : " + e.getMessage());
                    }
                } else {
                    err.println(EcomCommandsConstantes.INCORRECT_NUMBER_ARGS);
                }
            } else if (arg.equals("-remove")) {
                if (true != _context.getVar("isAdmin")) {
                    throw new InsuffisantPrivilegeException();
                }
                if (cmd.countTokens() == 1) {
                    try {
                        Long id = Long.valueOf(cmd.nextToken());
                        ecomAdminBean.removeProductcategory(id);
                        result.append("Productcategory whith id : ").append(id).append(" deleted");
                    } catch (Exception ex) {
                        err.println("Error with productcategory deletion : " + ex.getMessage());
                    }
                } else {
                    err.println(EcomCommandsConstantes.INCORRECT_NUMBER_ARGS);
                }
            } else {
                err.println(arg + " : This arg is not known for productcategory command");
            }
        }
        return result.toString();
    }

    private String printList(PrintStream out, Set<ProductcategoryBean> categories, Outputs currentOutput) throws IOException {
        StringBuilder res = new StringBuilder();
        if (currentOutput.equals(Outputs.XML)) {
            Element categorie = new Element("categories");
            Document document = new Document(categorie);

            for (ProductcategoryBean b : categories) {
                categorie.addContent(createXMLNode(b));
            }
            XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
            res.append(sortie.outputString(document));
        } else if (currentOutput.equals(Outputs.TEXT)) {
            for (ProductcategoryBean category : categories) {
                res.append(category).append("\n");
            }
        }
        else {
            res.append("Output format '").append(currentOutput).append("' is not implementing for this command");
        }
        return res.toString();
    }

    private Element createXMLNode(ProductcategoryBean categorie) {
        Element category = new Element("category");
        Attribute id = new Attribute("id", String.valueOf(categorie.getIdProductcategory()));
        category.setAttribute(id);
        category.setText(categorie.getName());
        return category;
    }

  
}
